package me.pearjelly.pmc.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import me.pearjelly.pmc.util.Logger;
import me.pearjelly.pmc.util.PmsHelper;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.springframework.jdbc.core.RowMapper;

public class DocumentMapper implements RowMapper<Document> {
	private static final Logger log = new Logger();
	@Override
	public Document mapRow(ResultSet rs, int i) throws SQLException {
		Document doc = new Document();
		doc.add(new Field("id",String.valueOf(rs.getLong("ID")),Store.YES,Index.NOT_ANALYZED));
		doc.add(new Field("name", rs.getString("PICGROUP_NAME"), Store.YES, Index.ANALYZED));
		doc.add(new Field("desc", rs.getString("PICGROUP_DESC") == null ? "" : rs.getString("PICGROUP_DESC"), Store.YES, Index.ANALYZED));
		doc.add(new Field("pri", String.valueOf(rs.getInt("PICGROUP_PRIORITY")), Store.YES, Index.NOT_ANALYZED));
		doc.add(new Field("mtime", String.valueOf(rs.getDate("PICGROUP_MTIME").getTime()), Store.YES, Index.NOT_ANALYZED));		
		doc.add(new Field("cateId", rs.getString("CATE_ID"), Store.YES, Index.NOT_ANALYZED));
		String cateRela = rs.getString("CATE_RELA");
		if(cateRela != null && cateRela.length() > 0){
			String[] relaCateIds = cateRela.split("\\|");
			for(String cateId: relaCateIds){
				if(cateId.trim().length() >0 ){
					doc.add(new Field("cateId", cateId.trim(), Store.YES, Index.NOT_ANALYZED));
				}
			}
		}		
		doc.add(new Field("domain", rs.getString("CATE_DOMAIN") == null ? "" : rs.getString("CATE_DOMAIN"), Store.YES, Index.NO));
		doc.add(new Field("count", String.valueOf(rs.getInt("PICCOUNT")), Store.YES, Index.NO));
		doc.add(new Field("imguri", PmsHelper.genImgUri(rs.getLong("FIRSTPIC_ID"),rs.getString("FIRSTPIC_EXT")), Store.YES, Index.NO));
		log.debug("Find document : %s", doc);
		return doc;
	}
}
